package com.redsoft.epip.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.redsoft.epip.util.ImgCompress;
import com.redsoft.spirit.entity.JsonResult;

/**
 * 为富文本编辑器提供的上传图片的Controller
 * 
 * <pre>
 * 为富文本编辑器提供的上传图片的Controller
 * </pre>
 * 
 * @author
 * @since 1.0
 */
@RestController
@Validated
public class ImageController {

	@Value("${web.upload-path}")
	private String path;

	@Value("${web.upload-url}")
	private String url;

	@PostMapping(value = "/**/images/editors/{modelName}")
	public String uploadImg(HttpServletRequest request, HttpServletResponse response, @PathVariable String modelName)
			throws Exception {
		response.setContentType("textml;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		Part part = request.getPart("wangEditorPasteFile");// myFileName是文件域的name属性值

		if (part == null) {
			part = request.getPart("wangEditorH5File");
		}
		// 文件类型限制
		String[] allowedType = { "image/bmp", "image/gif", "image/jpeg", "image/png" };
		boolean allowed = Arrays.asList(allowedType).contains(part.getContentType());
		if (!allowed) {
			return new JsonResult(null, "不支持的类型").failure().toString();
		}

		// 图片大小限制
		if (part.getSize() > 5 * 1024 * 1024) {
			return new JsonResult(null, "图片大小不能超过5M").failure().toString();
		}
		// 包含原始文件名的字符串
		String fi = part.getHeader("content-disposition");

		// 提取文件拓展名
		String fileNameExtension = fi.substring(fi.indexOf("."), fi.length() - 1);

		String modelPath = path + "editors/" + modelName + "/";

		File folder = new File(modelPath);

		if ((!folder.exists()) || (!folder.isDirectory())) {
			folder.mkdirs();
		}

		// 生成实际存储的真实文件名
		String realName = UUID.randomUUID().toString() + fileNameExtension;

		part.write(modelPath + realName);

		// 执行压缩图片的方法
		ImgCompress imgCom = new ImgCompress(modelPath + realName);

		File picture = new File(modelPath + realName);
		BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
		imgCom.resizeFix(sourceImg.getWidth(), sourceImg.getHeight());

//		String qnUrl = qnUpload(modelPath + realName);

//		return "http://ou3qfdc18.bkt.clouddn.com/" + qnUrl;
		return url + "editors/" + modelName + "/" + realName;
	}

	/**
	 * 即时上传头像.
	 * 
	 * <pre>
	 * 	即时上传头像,只上传按传过来的模块名存到不同的文件夹中.
	 * </pre>
	 * 
	 * @author
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/**/images/avatars/{modelName}")
	public String uploadCompanyAvatar(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String modelName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		Part part = request.getPart("file");// myFileName是文件域的name属性值
		// 文件类型限制
		String[] allowedType = { "image/bmp", "image/gif", "image/jpeg", "image/png" };
		boolean allowed = Arrays.asList(allowedType).contains(part.getContentType());
		if (!allowed) {
			// response.getWriter().write("error|不支持的类型");
			return new JsonResult(null, "不支持的类型").failure().toString();
		}
		// 图片大小限制
		if (part.getSize() > 5 * 1024 * 1024) {
			// response.getWriter().write("error|图片大小不能超过5M");
			return new JsonResult(null, "图片大小不能超过5M").failure().toString();
		}
		// 包含原始文件名的字符串
		String fi = part.getHeader("content-disposition");

		// 提取文件拓展名
		String fileNameExtension = fi.substring(fi.indexOf("."), fi.length() - 1);

		String modelPath = path + "avatars/" + modelName + "/";

		File folder = new File(modelPath);

		if ((!folder.exists()) || (!folder.isDirectory())) {
			folder.mkdirs();
		}

		// 生成实际存储的真实文件名
		String realName = UUID.randomUUID().toString() + fileNameExtension;

		part.write(modelPath + realName);

		// 执行压缩图片的方法
		ImgCompress imgCom = new ImgCompress(modelPath + realName);

		File picture = new File(modelPath + realName);
		BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
		imgCom.resizeFix(sourceImg.getWidth(), sourceImg.getHeight());

//		String qnUrl = qnUpload(modelPath + realName);

//		return "http://ou3qfdc18.bkt.clouddn.com/" + qnUrl;
		 return url + "avatars/" + modelName + "/" + realName;
	}

	public String qnUpload(String realPath) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		// ...其他参数参考类注释

		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = "-v4yPaj_q3gGhpkwy5jwKO075XwMdv4DXKxZPevc";
		String secretKey = "NnLHLKcxLut9e7bzUfcGOQa6Xi2GLDWhbBkWJfrf";
		String bucket = "savor";
		// 如果是Windows情况下，格式是 D:\\qiniu\\test.png
		String localFilePath = realPath;
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;

		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);

		try {
			Response response = uploadManager.put(localFilePath, key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			return putRet.key;
		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());
			try {
				System.err.println(r.bodyString());
			} catch (QiniuException ex2) {
				// ignore
			}
			return "";
		}
	}
}
